package com.tcdp.daos;

import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import com.tcdp.models.Gallery;

public class GalleryDao extends AbstractDao {

	public Gallery findById(int id){
		Gallery gallery = em.find(Gallery.class, id);
		return gallery;
	}
	
	public Gallery findByUrl(String url){
		Gallery gallery = null;
		
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Gallery> cq = cb.createQuery(Gallery.class);
		Root<Gallery> root = cq.from(Gallery.class);
		cq.select(root).where(cb.equal(root.<String>get("galleryUrl"), url));
		TypedQuery<Gallery> tq = em.createQuery(cq);
		
		try{
			gallery = tq.getSingleResult();
		}catch(NoResultException e){
			throw404(e);
		}
		
		return gallery;
	}
	
}
